import re
from django import forms
from django.core.exceptions import ValidationError
from app01 import models
from app01.utils.bootstrap import BootStrapModelForm


class UserModelForm(BootStrapModelForm):
    name = forms.CharField(min_length=3, max_length=8, label='用户名', error_messages={'required': '用户名不能为空',
                                                                                       'min_length': '用户名长度不能小于3',
                                                                                       'max_length': '用户名长度不能大于8'})

    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'account', 'create_time', 'depart', 'gender']  # '__all__'


class PrettynumModelForm(BootStrapModelForm):
    # 验证方式一
    # mobile = forms.CharField(
    #     label='手机号',
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式不正确')])

    class Meta:
        model = models.PrettyNum
        fields = '__all__'

    def clean_mobile(self):
        # 验证方式二
        mobile = self.cleaned_data.get('mobile')
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=mobile).exists()
        if exists:
            raise ValidationError('手机号已存在')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            self.add_error('mobile', '手机号格式不正确')
        return mobile
